package com.ziyun.pop.mall.base.exception;

import com.service.common.exception.BaseException;
import com.service.common.protocol.BaseResult;
import com.service.common.protocol.ResultCode;
import com.utility.NumberUtil;
import com.utility.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author:chenxiaoyi
 * @Date:2018/10/4 16:13
 */
@ControllerAdvice
public class PopGlobalExceptionHandler {

    private static Logger _log = LoggerFactory.getLogger(PopGlobalExceptionHandler.class);

    /**
     * 业务异常类
     * @param req
     * @param e
     * @returne
     */
    @ResponseBody
    @ExceptionHandler(value = BaseException.class)
    public BaseResult<?> defaultErrorHandler(HttpServletRequest req, Exception e) {
        BaseException baseException = (BaseException) e;
        ResultCode resultCode = baseException.getResultCode();
        String message = resultCode == null ? baseException.getMessage() : resultCode.getMessage();
        BaseResult<?> dto = null;
        _log.error(message);
        if (resultCode == null) {
            if (NumberUtil.isNumber(message)) {
                dto = BaseResult.error(Integer.valueOf(message), e.getClass().getName());
            } else {
                message = StringUtils.defaultIfBlank(message, ResultCode.DATA_ERROR.getMessage());
                dto = BaseResult.error(ResultCode.DATA_ERROR.getCode(), message);
            }
        } else {
            dto = BaseResult.error(resultCode);
        }
        return dto;
    }

}
